<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1200px" @open="open" @close="close">
    <el-form class="tl-form" ref="dealform" :model="model" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="项目级别" prop="projectlevel2" :rules="rules.rulesForInfo">
            <el-select v-model="model.projectlevel2" filterable clearable>
              <el-option v-for="item in codeModel.projectlevelList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
      <el-row style="margin-left:1px">
        <el-col :span="24">
          <el-form-item label="变更内容" prop="changecontent" :rules="rules.rulesForInfo">
            <el-input v-model="model.changecontent" type="textarea" :rows="5" maxlength="1000" show-word-limit style="width:100%"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="margin-left:1px">
        <el-col :span="24">
          <el-form-item label="变更原因" prop="changereason" :rules="rules.rulesForInfo">
            <el-input v-model="model.changereason" type="textarea" :rows="5" maxlength="1000" show-word-limit style="width:100%"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-tabs type="border-card" v-model="tabName">
        <el-tab-pane label="立项信息" name="projectbasicinfo">
          <el-row>
            <el-col :span="12">
              <el-form-item label="机会点" prop="chanceclue2">
                <el-input v-model="model.chanceclue2" class="tl-ref-selector" disabled>
                  <el-button slot="append" type="primary" icon="el-icon-search" @click="openChanceclueDialog"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目编号" prop="projectcode2">
                <el-input v-model="model.projectcode2" :disabled="true" placeholder="系统自动生成"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectname2" :rules="rules.rulesForInfo">
                <el-input v-model="model.projectname2"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="可参与金额" prop="participatemoney2" :rules="rules.rulesForInfo">
                <el-input-number v-model="model.participatemoney2" controls-position="right" :step="1" :min="0" :precision="2" style="width: 91%"></el-input-number><span>万元</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目级别" prop="projectlevel2" :rules="rules.rulesForInfo">
                <el-select v-model="model.projectlevel2" filterable clearable>
                  <el-option v-for="item in codeModel.projectlevelList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购模式" prop="purchasepattern2" :rules="rules.rulesForInfo">
                <el-select v-model="model.purchasepattern2" filterable clearable>
                  <el-option v-for="item in codeModel.MpmPurchasePatternList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划开始日期" prop="planstartdate2" :rules="rules.rulesForInfo">
                <el-date-picker v-model="model.planstartdate2" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="planStart">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划结束日期" prop="planenddate2" :rules="rules.rulesForInfo">
                <el-date-picker v-model="model.planenddate2" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="planEnd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="创建部门" prop="deptname2" :rules="rules.rulesForInfo">
                <tl-ref-dept v-model="model.deptname2" :initDisplayData.sync="model.deptname2" dataType="code" nameType="fullname" @confirm="onSelectDept" :singleSelect="true" :externalQueryParam="{ qry_enabled: 1 }">
                </tl-ref-dept>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="项目周期" prop="bidcycle2">
                <el-input v-model="model.bidcycle2" style="width: 93%" placeholder="系统自动计算"></el-input><span>天</span>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="发标日期" prop="bidbegindate2" :rules="rules.rulesForInfo">
                <el-date-picker v-model="model.bidbegindate2" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="截标日期" prop="bidenddate2" :rules="rules.rulesForInfo">
                <el-date-picker v-model="model.bidenddate2" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目经理" prop="projectmanager2" :rules="rules.rulesForInfo">
                <el-input v-model="model.projectmanager2"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Sponsor" prop="sponsorcode2">
                <tl-ref-user v-model="model.sponsorcode2" :initDisplayData.sync="model.sponsor2" dataType="code" :singleSelect="true">
                </tl-ref-user>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="Owner" prop="ownercode2">
                <tl-ref-user v-model="model.ownercode2" :initDisplayData.sync="model.owner2" dataType="code" :singleSelect="true">
                </tl-ref-user>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="决策组人员" prop="decisionusername2" :rules="rules.rulesForInfo">
                <el-input v-model="model.decisionusername2" class="tl-ref-selector">
                  <el-button slot="append" type="primary" icon="el-icon-search" @click="openMpmProjectResourcePoolDialog" v-if="!disableSave"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-row style="margin-bottom:20px;margin-top:20px;" v-if="model.productrange2">
              <div>
                <div class="formLine"><span class="formLineTitle">【涉及产品范围】包含产品类别，金额</span></div>
              </div>
            </el-row>
            <el-row v-for="(item,index) in model.productrange2" :key="index">
              <el-col :span="12">
                <el-form-item label="产品类别">
                  <el-input v-model="item.productType" disabled class="tl-ref-selector">
                    <el-input v-model="item.productType"></el-input>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="金额">
                  <el-input v-model="item.productMoney" class="tl-ref-selector">
                    <el-input v-model="item.productMoney"></el-input>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="项目背景概述" prop="background2">
                <el-input v-model="model.background2" type="textarea" :rows="4" maxlength="1000" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="项目目标" prop="target2">
                <el-input v-model="model.target2" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="总体策划" prop="summary2">
                <el-input v-model="model.summary2" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-collapse>
            <el-collapse-item title="【单据】申请信息">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人姓名" prop="username" :rules="rules.rulesForInfo">
                    <el-input v-model="model.username" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人工号" prop="usercode">
                    <el-input v-model="model.usercode" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人部门" prop="applydeptname">
                    <el-input v-model="model.applydeptname" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人公司" prop="applyorgname">
                    <el-input v-model="model.applyorgname" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
        <el-tab-pane label="客户信息" name="projectcustomerinfo">
          <div style="margin-top: 1px; margin-left: -20px" class="mancomment">
            <el-row>
              <el-col :span="12">
                <el-form-item label="客户名称" prop="clientname2" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientname2" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户部门" prop="clientdept2" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientdept2" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="客户决策链支持度" prop="clientsupport2" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientsupport2"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="客户需求分析" prop="clientdemand2" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientdemand2" type="textarea" :rows="6" maxlength="1000" show-word-limit>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="客户决策模式" prop="decisionmode2" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.decisionmode2" type="textarea" :rows="6" maxlength="1000" show-word-limit>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="竞争对手" name="projectcompetitorinfo">
          <div style="margin-top: 1px; margin-left: -50px" class="mancomment">
            <el-row>
              <el-col :span="24">
                <el-form-item label="主要竞争对手" prop="competitor2" :rules="rules.rulesForCompetitorInfo">
                  <el-input v-model="model.competitor2" type="textarea" :rows="8" maxlength="1000" show-word-limit>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="SWOT分析" prop="swot2" :rules="rules.rulesForCompetitorInfo">
                  <el-input v-model="model.swot2" type="textarea" :rows="8" maxlength="1000" show-word-limit></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <tl-approval-history ref="history" sourceType="MpmProjectChange" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit">取消</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" :disabled="disableSave">
        <svg-icon icon-class="save" />保存
      </el-button>
      <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" :disabled="disableApproval">
        <svg-icon icon-class="send" />变更审批
      </el-button>
      <tl-attachment sourceType="MpmProjectChange" :sourceId="model.id" :editable="stateEdit"></tl-attachment>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory">
        <svg-icon icon-class="list" />审批历史
      </el-button>
      <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableEditSubmit" :disabled="disableDelApproval">
        <svg-icon icon-class="undo" />取消审批
      </el-button>
    </div>
    <tlmpmProject-manager-pool-ref ref="mpmProjectManagerPoolRef" @confirm="getMpmProjectManagerData" :isSingleSelect="true" :externalQueryParam="externalMQueryParamForPool">
    </tlmpmProject-manager-pool-ref>
    <tlmpmProject-resource-pool-ref ref="mpmProjectResourcePoolRef" @confirm="getMpmProjectResourceData" :isSingleSelect="false" :externalQueryParam="externalDQueryParamForPool">
    </tlmpmProject-resource-pool-ref>
    <tlchange-ref ref="changeRef" @confirm="getChanceclueData" :isSingleSelect="true" :fieldKey="rowKeyStr">
    </tlchange-ref>
  </tl-sub-page>
</template>

<script>
/** mixins */

import { mixin_approval_edit } from "@tapui/mixins/mixin_approval_edit"
import { mixin_page_fields_custom } from "@misui/mixins/mixin_page_fields_custom"
/** 子组件 */
import { validateNull } from "@tapui/utils/validate"
import tlmpmProjectManagerPoolRef from "@/views/mpm/mpmProjectManagerPool/refList"
import tlmpmProjectResourcePoolRef from "@/views/mpm/mpmProjectResourcePool/refList"
import tlchangeRef from "@/views/mpm/mpmProject/refListChange"
import { filterObjectNull, rmbFormat } from '@tapui/utils/util'

/** 工具类 */
import {
  putAction,
  getAction,
  postAction,
  deleteAction
} from "@tapui/utils/http"
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit, mixin_page_fields_custom],
  components: {
    tlmpmProjectManagerPoolRef,
    tlmpmProjectResourcePoolRef,
    tlchangeRef
  },
  data() {
    var validateForTab = (rule, value, callback) => {
      if (!value) {
        this.tabName = rule.tabname
        return callback(new Error("请输入内容"))
      } else {
        return callback()
      }
    }
    return {
      moduleTitle: "项目立项变更",
      urlPrefix: "/mpm/projectChange/",
      url: {
        // 额外的url
        queryOrgByDeptId: "/mpm/project/queryOrgByDeptId",
        list: "/cbo/approvalNodeIns/list",
        projectChange: "project/change/insert"
      },
      tabName: "projectbasicinfo",
      sorterInfo: {
        // 排序参数
        sidx: "id",
        sord: "desc"
      },
      midChangePoint: true,
      attactives: ["1"],
      datas: [],
      pageInfo: {
        // 分页参数
        currentPage: 1, // 当前页面
        pageSize: 10, // 每页记录数
        pageSizes: ["10", "50", "100"],
        totalCount: 0 // 总数
      },
      rowKeyStr: "CODE",
      loading: false,
      oldprojectlevel: '',
      visible: false,
      listMode: true,
      projectmodel: '',
      oldmodel: '',
      externalMQueryParamForPool: {},
      externalDQueryParamForPool: {},
      // 项目立项规则校验重写
      addRules: {
        // 基本信息TAB表单校验
        rulesForInfo: [
          {
            validator: validateForTab,
            tabname: "projectbasicinfo",
            trigger: "change"
          },
          { required: "true", message: "请输入内容", trigger: "change" }
        ],
        // 案例概述TAB表单验证
        rulesForCustomeryInfo: [
          {
            validator: validateForTab,
            tabname: "projectcustomerinfo",
            trigger: "change"
          },
          { required: "true", message: "请输入内容", trigger: "change" }
        ],
        rulesForCompetitorInfo: [
          {
            validator: validateForTab,
            tabname: "projectcompetitorinfo",
            trigger: "change"
          },
          { required: "true", message: "请输入内容", trigger: "change" }
        ]
      }
    }
  },
  props: {},
  methods: {
    loaded() {
      this.oldprojectlevel = this.model.projectlevel2
    },
    saveProjectLevelInfo(resolve, reject) {
      const {
        id,
        projectlevel2,
        deptcode
      } = this.model
      if (projectlevel2 !== this.oldprojectlevel) {
        const data = {
          id: id,
          newprojectlevel: projectlevel2,
          oldprojectlevel: this.oldprojectlevel
        }
        postAction('/mpm/projectChange/updateLevelHistory', data)
          .then(res => {
            if (res.success) {
              resolve()
            } else {
              this.$tap.alert(res.message, 'warning')
              reject()
            }
          })
      }
      const param = {
        id,
        projectlevel2,
        deptcode
      }
      putAction(this.url.edit, param)
        .then(res => {
          if (res.success) {
            resolve()
          } else {
            this.$tap.alert(res.message, 'warning')
            reject()
          }
        })
        .catch(err => {
          this.$tap.alert('修改项目级别信息失败，请联系系统管理员', 'warning')
          reject()
        })
    },
    saveChangeApprovalTypeInfo(resolve, reject) {
      const { id, approvaltype2, deptcode } = this.model
      if (!approvaltype2) {
        this.$tap.alert('请选择审批类型')
        reject()
      }
      const param = {
        id,
        approvaltype2,
        deptcode
      }
      putAction(this.url.edit, param)
        .then(res => {
          if (res.success) {
            resolve()
          } else {
            this.$tap.alert(res.message, 'warning')
            reject()
          }
        })
        .catch(err => {
          this.$tap.alert('保存审批类型信息失败，请联系系统管理员', 'warning')
          reject()
        })
    },
    planStart(e) {
      var a = new Date(this.model.planstartdate)
      var b = new Date()
    },
    planEnd(e) {
      if (
        this.model.planstartdateForChange === "" ||
        typeof this.model.planstartdateForChange === "undefined"
      ) {
        this.$tap.alert("请先选择计划开始日期！", "warning")
        this.$set(this.model, "planenddateForChange", "")
        this.$set(this.model, "bidcycleForChange", "")
        return
      }
      var c = new Date(this.model.planenddateForChange).getTime()
      var d = new Date(this.model.planstartdateForChange).getTime()
      if (c < d) {
        this.$tap.alert("开始日期不得大于结束日期。", "warning")
        this.$set(this.model, "planenddateForChange", "")
        this.$set(this.model, "bidcycleForChange", "")
        return
      }
      var a = c - d
      var days = Math.ceil(a / (1000 * 3600 * 24)) + 1
      this.$set(this.model, "bidcycle", days)
      // 计划结束日期存储为选择日期的的23：59：59
      let date = new Date(c)
      let timeDate = ""
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      let h = 23 + ':'
      let m = 59 + ':'
      let s = 59
      timeDate = Y + M + D + h + m + s
      this.$set(this.model, 'planenddate', timeDate)
    },
    assignDefaultValue() {
      if (this.isAdd) {
        this.$set(this.model, "chanceclue2", this.projectmodel.chanceclue)
        this.$set(this.model, "projectcode2", this.projectmodel.projectcode)
        this.$set(this.model, "projectname2", this.projectmodel.projectname)
        this.$set(this.model, "participatemoney2", this.projectmodel.participatemoney)
        this.$set(this.model, "projectlevel2", this.projectmodel.projectlevel)
        this.$set(this.model, "purchasepattern2", this.projectmodel.purchasepattern)
        this.$set(this.model, "planstartdate2", this.projectmodel.planstartdate)
        this.$set(this.model, "planenddate2", this.projectmodel.planenddate)
        this.$set(this.model, "deptname2", this.projectmodel.deptname)
        this.$set(this.model, "bidcycle2", this.projectmodel.bidcycle)
        this.$set(this.model, "bidbegindate2", this.projectmodel.bidbegindate)
        this.$set(this.model, "bidenddate2", this.projectmodel.bidenddate)
        this.$set(this.model, "projectmanager2", this.projectmodel.projectmanager)
        this.$set(this.model, "sponsor2", this.projectmodel.sponsor)
        this.$set(this.model, "sponsorcode2", this.projectmodel.sponsorcode)
        this.$set(this.model, "owner2", this.projectmodel.owner)
        this.$set(this.model, "ownercode2", this.projectmodel.ownercode)
        this.$set(this.model, "decisionusername2", this.projectmodel.decisionusername)
        this.$set(this.model, "productrange2", this.projectmodel.productrange)
        this.$set(this.model, "background2", this.projectmodel.background)
        this.$set(this.model, "target2", this.projectmodel.target)
        this.$set(this.model, "summary2", this.projectmodel.summary)
        this.$set(this.model, "username", this.projectmodel.username)
        this.$set(this.model, "usercode", this.projectmodel.usercode)
        this.$set(this.model, "deptname", this.projectmodel.deptname)
        this.$set(this.model, "deptcode", this.projectmodel.deptcode)
        this.$set(this.model, "applydeptname", this.projectmodel.applydeptname)
        this.$set(this.model, "applydeptcode", this.projectmodel.applydeptcode)
        this.$set(this.model, "applyorgname", this.projectmodel.applyorgname)
        this.$set(this.model, "clientname2", this.projectmodel.clientname)
        this.$set(this.model, "clientdept2", this.projectmodel.clientdept)
        this.$set(this.model, "clientsupport2", this.projectmodel.clientsupport)
        this.$set(this.model, "clientdemand2", this.projectmodel.clientdemand)
        this.$set(this.model, "decisionmode2", this.projectmodel.decisionmode)
        this.$set(this.model, "competitor2", this.projectmodel.competitor)
        this.$set(this.model, "swot2", this.projectmodel.swot)
      }
    },
    // loaded() {
    //   页面加载完毕执行
    //     if (!this.isAdd && this.model.docno) {
    //       this.title = this.title + `（单据编号：${this.model.docno}）`
    //     }
    // },
    // beforeApproval() {
    //   // 该地方判断变更后的值
    //   if (
    //     this.model.projectmanagercodeForChange ===
    //     this.model.sponsorcodeForChange ||
    //     this.model.projectmanagercodeForChange ===
    //     this.model.ownercodeForChange ||
    //     this.model.sponsorcodeForChange === this.model.ownercodeForChange
    //   ) {
    //     this.$tap.alert(
    //       "项目经理、sponsor和owner不能重复，请确认！",
    //       "warning"
    //     )
    //     return false
    //   } else {
    //     return true
    //   }
    // },
    /** 提交审批 */
    // doSubmitApproval() {
    //   if (!this.url.submit) {
    //     this.$tap.alert("请设置审批地址!", "warning")
    //     return
    //   }
    //   let fileValidate = true
    //   this.$refs.form.validate((valid) => {
    //     if (!valid) {
    //       fileValidate = false
    //     }
    //   })
    //   if (!fileValidate) {
    //     return
    //   }
    //   if (!this.beforeApproval()) {
    //     return
    //   }
    //   this.submitLoading = true
    //   this.$tap
    //     .confirm("确定提交审批吗？提交后，单据内容不可修改！")
    //     .then((_) => {
    //       this.$set(this.model, "projectstate", 0)
    //       if (this.isAdd) {
    //         this.saveLoading = true
    //         // 增加唯一单号
    //         this.$set(this.model, "billuid", this.uid)
    //         postAction(this.url.add, this.model)
    //           .then((res) => {
    //             if (res.success) {
    //               this.$tap.message("添加成功", "success")
    //               this.queryData(res.result.id)
    //               this.isAdd = false
    //               putAction(this.url.submit, this.model).then((res) => {
    //                 if (res.success) {
    //                   this.$emit("refresh")
    //                   this.$tap.message(res.message, "success")
    //                   this.queryData(this.model.id)
    //                   this.afterApproval()
    //                 } else {
    //                   this.$tap.alert(res.message, "warning")
    //                 }
    //                 this.submitLoading = false
    //               })
    //             } else {
    //               this.$tap.alert(res.message, "warning")
    //             }
    //             this.afterSubmit()
    //             this.saveLoading = false
    //           })
    //           .catch((err) => {
    //             this.saveLoading = false
    //           })
    //       } else {
    //         this.saveLoading = true
    //         putAction(this.url.edit, this.model)
    //           .then((res) => {
    //             if (res.success) {
    //               putAction(this.url.submit, this.model).then((res) => {
    //                 if (res.success) {
    //                   this.$emit("refresh")
    //                   this.$tap.message(res.message, "success")
    //                   this.queryData(this.model.id)
    //                   this.afterApproval()
    //                 } else {
    //                   this.$tap.alert(res.message, "warning")
    //                 }
    //                 this.submitLoading = false
    //               })
    //             } else {
    //               this.$tap.alert(res.message, "warning")
    //             }
    //             this.afterSubmit()
    //             this.saveLoading = false
    //           })
    //           .catch((err) => {
    //             this.saveLoading = false
    //           })
    //       }
    //     })
    //     .catch((_) => {
    //       this.submitLoading = false
    //     })
    // },
    /** 执行编辑提交 */
    doEdit() {
      this.saveLoading = true
      putAction(this.url.edit, this.model)
        .then((res) => {
          if (res.success) {
            this.$emit("refresh")
          } else {
            this.$tap.alert(res.message, "warning")
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    // 选择项目所属部门
    onSelectDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const { id, code, fullname } = selectedDept
      this.$set(this.model, "deptcode", code)
      this.$set(this.model, "deptname", fullname)
      const param = {
        deptId: id
      }
      getAction(this.url.queryOrgByDeptId, param).then((res) => {
        if (res.success) {
          const { code: orgcode, name: orgname } = res.result
          this.$set(this.model, "orgcode", orgcode)
          this.$set(this.model, "orgname", orgname)
        } else {
          this.$tap.alert("已选部门关联公司信息错误，请联系系统管理员")
        }
      })
    },
    open() {
      this.model = {}
      this.$nextTick(() => {
        this.getFieldsCustomSetting("projectpolymerization", "el-form")
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = "新增" + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, "enabled", 1)
            this.$set(this.model, "sortcode", 0)
            this.assignDefaultValue()
            this.loaded()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = "编辑" + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        } else {
          this.title = "查看" + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        }
      })
      this.datas = []
      this.loadData({ currentPage: 1 })
    },
    /** 加载审批历史列表数据 */
    loadData(paramMap) {
      if (
        validateNull(paramMap) === false &&
        Object.keys(paramMap).indexOf("currentPage") > -1
      ) {
        this.pageInfo.currentPage = paramMap["currentPage"]
      }
      // 查询条件
      this.sorterInfo.sidx = "approvaldate"
      var params = this.getQueryParams()
      // 数据查询
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.datas = res.result.dataList
            this.pageInfo.totalCount = res.result.totalCount
          } else {
            this.$tap.alert(res.message, "warning")
          }
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    /** 执行查询 */
    doQuery() {
      this.loadData({ currentPage: 1 })
    },
    /** 获取查询参数 */
    // getQueryParams() {
    //   let param = {
    //     qry_sourcetype: "MpmProjectChange",
    //     qry_sourceid: 0
    //   }
    //   if (!this.isAdd) {
    //     param.qry_sourceid = this.id
    //   }
    //   Object.assign(param, this.sorterInfo)
    //   param.currentPage = this.pageInfo.currentPage
    //   param.pageSize = this.pageInfo.pageSize
    //   return param
    // },
    /** 获取查询参数 */
    getQueryParams() {
      let param = {}
      if (this.superQueryParams) {
        param['superQueryParams'] = encodeURI(this.superQueryParams)
      }
      Object.assign(param, this.queryParam, this.sorterInfo, this.filtersInfo)
      param.currentPage = this.pageInfo.currentPage
      param.pageSize = this.pageInfo.pageSize
      return filterObjectNull(param)
    },
    /** 表格列排序 */
    doSortChange(columnInfo, prop, order) {
      if (columnInfo.column === null) {
        return
      }
      // 不排序
      if (validateNull(columnInfo.order)) {
        this.loadData({})
        return
      }
      // 升序或者降序排序
      if (columnInfo.column.sortBy) {
        this.sorterInfo.sidx = columnInfo.column.sortBy
      } else {
        this.sorterInfo.sidx = columnInfo.prop
      }
      this.sorterInfo.sord = columnInfo.order.replace("ending", "")
      this.loadData({})
    },
    /** 每页大小改变 */
    doChangeSize(val) {
      if (this.pageInfo.pageSize !== val) {
        this.pageInfo.pageSize = val
        this.pageInfo.currentPage = 1
        this.loadData({})
      }
    },
    /** 页面跳转 */
    doChangeIndex(val) {
      if (this.pageInfo.currentPage !== val) {
        this.pageInfo.currentPage = val
        this.loadData({})
      }
    },
    drawDiagram(map) {
      /* eslint-disable*/
      $("#history-myflow").html("")
      let restore = map.strdiagram
      restore = restore.replace(/'/g, '"')
      if (restore !== "") {
        restore = JSON.parse(restore)
      }
      let history = map.strhistory
      history = history.replace(/'/g, '"')
      history = history.replace(/activeRects/g, '"activeRects"')
      history = history.replace(/historyRects/g, '"historyRects"')
      history = history.replace(/rects/g, '"rects"')
      history = history.replace(/paths/g, '"paths"')
      history = history.replace(/code/g, '"code"')
      if (history !== "") {
        history = JSON.parse(history)
      }
      $("#history-myflow").myflow(
        $.extend(false, {
          basePath: "",
          restore: restore,
          editable: false,
          ...history,
        })
      );
    },
    // 项目级别变更后，清空项目经理和决策组--2-7todo 暂时取消
    clear() {
      if (this.model.projectmanagercode || this.model.decisionusercode) {
        this.$set(this.model, "projectmanagercode", "")
        this.$set(this.model, "projectmanager", "")
        this.$set(this.model, "decisionusercode", "")
        this.$set(this.model, "decisionusername", "")
      }
    },
    /** 打开项目经理参照 */
    openMpmProjectManagerPoolDialog() {
      const { projectlevel, projecttype } = this.model
      if (!projectlevel) {
        this.$tap.alert("请先选择项目级别！", "warning")
        this.$refs.mpmProjectManagerPoolRef.visible = false
      } else {
        this.externalMQueryParamForPool = {
          projectlevel: projectlevel,
          projecttype: projecttype,
        };
        this.$refs.mpmProjectManagerPoolRef.visible = true
      }
    },
    /** 获取项目经理参照数据 */
    getMpmProjectManagerData(selectionRow, selectKey, selectionValue) {
      this.$set(
        this.model,
        "projectmanagercodeForChange",
        selectionRow.managercode
      )
      this.$set(
        this.model,
        "projectmanagerForChange",
        selectionRow.managername
      )
    },
    /** 打开决策组成员参照 */
    openMpmProjectResourcePoolDialog() {
      const { projectlevel, projecttype } = this.model
      if (!projectlevel) {
        this.$tap.alert("请先选择项目级别！", "warning")
        this.$refs.mpmProjectResourcePoolRef.visible = false
      } else {
        this.externalDQueryParamForPool = {
          projectlevel: projectlevel,
          projecttype: projecttype,
        };
        this.$refs.mpmProjectResourcePoolRef.visible = true
      }
    },
    /** 获取决策组成员参照数据 */
    getMpmProjectResourceData(selectionRow, selectKey, selectionValue) {
      if (selectionRow.length > 0) {
        let code = []
        let name = []
        selectionRow.forEach((element) => {
          code.push(element.usercode)
          name.push(element.username)
        })
        let codes = "," + code.join(",") + ","
        let names = name.join(",")
        this.$set(this.model, "decisionusercodeForChange", codes)
        this.$set(this.model, "decisionusernameForChange", names)
      } else {
        let codes = "," + selectionRow.usercode + ","
        let names = selectionRow.username
        this.$set(this.model, "decisionusercodeForChange", codes)
        this.$set(this.model, "decisionusernameForChange", names)
      }
    },
    /** 打开机会点参照 */
    openChanceclueDialog() {
      this.$refs.changeRef.visible = true
    },
    /** 获取机会点参照数据 */
    getChanceclueData(selectionRow, selectKey, selectionValue) {
      console.log(selectionRow)
      //单个机会点
      if (!Array.isArray(selectionRow)) {
        this.$set(this.model, "chanceclueForChange", selectionRow.CODE)
        this.$set(
          this.model,
          "projectnameForChange",
          selectionRow.PROJECT_NAME
        )
        this.$set(
          this.model,
          "projectmanagerForChange",
          selectionRow.GARDENER_NAME
        )
        this.$set(
          this.model,
          "projectmanagercodeForChange",
          selectionRow.GARDENER_CODE
        )
        this.$set(
          this.model,
          "deptnameForChange",
          selectionRow.DEPT_COMMON_CODE_1NAME
        )
        //从机会点获取到的creator_dept_code 作为创建部门编码(deptcode)，根据创建部门编码，走审批
        this.$set(
          this.model,
          "deptcodeForChange",
          selectionRow.CREATOR_DEPT_CODE
        )
        this.$set(
          this.model,
          "participatemoneyForChange",
          selectionRow.OUR_PROCDUCT_FUND
        )
        this.$set(this.model, "clientnameForChange", selectionRow.CLIENT_NAME);
        this.$set(
          this.model,
          "clientdeptForChange",
          selectionRow.CLIENT_DEPT_NAME
        )
        //获取产品类型，拼装产品金额，请求报文为json数组
        var proType = selectionRow.CATALOG2.split(",");
        var productScotts = [];
        proType.forEach((item, index) => {
          var productScott = {
            productType: item,
            productMoney: "",
          }
          productScotts.push(productScott);
        })
        this.$set(this.model, "productrangeForChange", productScotts);
        //多个机会点情况
      } else {
        //项目名称，可参与金额须手填
        this.midChangePoint = false;
        var chanceclue = "";
        var productScotts = []
        var productTypets = []
        //循环取值
        selectionRow.forEach((item, index) => {
          //填充机会点
          if (chanceclue.length > 0) {
            chanceclue = chanceclue + "," + item.CODE
          } else {
            chanceclue = item.CODE
          }
          //填充涉及产品范围，获取产品类型，拼装产品金额，请求报文为json数组
          var proType = item.CATALOG2.split(",")

          for (var i in proType) {
            productTypets.push(proType[i])
          }
        });
        var unqProType = []
        productTypets.forEach((item, index) => {
          console.log(unqProType.indexOf(productTypets[index]))
          if (unqProType.indexOf(productTypets[index]) == -1) {
            unqProType.push(item)
          }
        });
        unqProType.forEach((item, index) => {
          var productScott = {
            productType: item,
            productMoney: "",
          };
          productScotts.push(productScott)
        });
        this.$set(this.model, "productrangeForChange", productScotts)
        this.$set(this.model, "chanceclueForChange", chanceclue)
      }
    },
  },
};
</script>
<style scoped>
.formLine {
  position: relative;
  margin: 0 auto;
  width: 600px;
  height: 1px;
  background-color: #d4d4d4;
  text-align: center;
  font-size: 16px;
  color: rgba(101, 101, 101, 1);
}
.formLineTitle {
  position: absolute;
  left: 50%;
  background-color: #ffffff;
  padding: 0 15px;
  transform: translateX(-50%) translateY(-50%);
}
</style>
